package com.xusl.spring.proxy;

import com.xusl.spring.model.User;
import com.xusl.spring.service.UserService;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @Author: xusl
 * @Date: 2021/8/4 9:39 下午
 */
public class JDKProxy {

    private UserService userService;

    public JDKProxy(UserService userService) {
        this.userService = userService;
    }

    public void execute() {
        // 返回userService的代理对象
        UserService userServiceProxy = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(), userService.getClass().getInterfaces(), (proxy, method, args) -> {
            System.out.println("userService接口执行前置增强");

            Object result = method.invoke(userService, args);

            System.out.println("userService接口执行后置增强");

            // 被代理对象执行结果返回
            return result;
        });

        // 代理对象执行被代理对象的接口
        List<User> users = userServiceProxy.queryAll();

        // 打印结果
        System.out.println(users);
    }
}
